import React, { useState } from 'react';
import { Button, Space, Tag, Tooltip, Empty, message } from 'antd';
import { EditOutlined, DeleteOutlined, SettingOutlined, DownOutlined, UpOutlined, CopyOutlined, ArrowUpOutlined } from '@ant-design/icons';
import { Parameter, ParameterValue } from '../../types';

interface ParameterItemProps {
  parameter: Parameter;
  onEdit: () => void;
  onDelete: () => void;
  onSetValues: () => void;
  onPinToTop: () => void;
}

const ParameterItem: React.FC<ParameterItemProps> = ({
  parameter,
  onEdit,
  onDelete,
  onSetValues,
  onPinToTop
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  const handleCopyEnglishName = async () => {
    try {
      await navigator.clipboard.writeText(parameter.name_en);
      message.success('已复制');
    } catch (err) {
      // 降级方案：使用传统方法
      const textArea = document.createElement('textarea');
      textArea.value = parameter.name_en;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      message.success('已复制');
    }
  };
  const getTypeColor = (type: string) => {
    const colors: { [key: string]: string } = {
      integer: 'blue',
      float: 'green',
      boolean: 'orange',
      string: 'purple'
    };
    return colors[type] || 'default';
  };

  const getTypeText = (type: string) => {
    const texts: { [key: string]: string } = {
      integer: '整数',
      float: '浮点数',
      boolean: '布尔值',
      string: '字符串'
    };
    return texts[type] || type;
  };

  const formatParameterValue = (value: ParameterValue) => {
    const { value: val } = value;
    const { param_type } = parameter;
    
    switch (param_type) {
      case 'boolean':
        return val === 'true' ? '是' : val === 'false' ? '否' : val;
      case 'integer':
        return parseInt(val).toString();
      case 'float':
        return parseFloat(val).toString();
      default:
        return val;
    }
  };

  const renderParameterValues = () => {
    const values = parameter.values || [];
    
    if (values.length === 0) {
      return (
        <div style={{ 
          fontSize: '11px', 
          color: '#d9d9d9',
          fontStyle: 'italic'
        }}>
          暂无参数值
        </div>
      );
    }

    if (parameter.is_list) {
      // 列表参数：显示更多值，支持展开/收起
      const sortedValues = values.sort((a, b) => (a.list_index || 0) - (b.list_index || 0));
      const displayCount = isExpanded ? sortedValues.length : Math.min(10, sortedValues.length);
      const displayValues = sortedValues.slice(0, displayCount);
      const remainingCount = sortedValues.length - displayCount;
      
      return (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap', marginBottom: '6px' }}>
            <span style={{ fontSize: '12px', color: '#8c8c8c' }}>值:</span>
            {displayValues.map((value, index) => (
              <Tag 
                key={value.id} 
                color="purple" 
                style={{ 
                  fontSize: '11px', 
                  margin: 0,
                  borderRadius: '8px',
                  padding: '2px 8px',
                  lineHeight: '18px'
                }}
              >
                {formatParameterValue(value)}
              </Tag>
            ))}
            {remainingCount > 0 && !isExpanded && (
              <Tag color="orange" style={{ 
                fontSize: '11px', 
                margin: 0,
                borderRadius: '8px',
                padding: '2px 8px',
                lineHeight: '18px'
              }}>
                +{remainingCount}
              </Tag>
            )}
            {parameter.unit && (
              <span style={{ 
                background: 'linear-gradient(135deg, #f6ffed 0%, #f0f9e8 100%)',
                color: '#52c41a',
                padding: '3px 8px',
                borderRadius: '4px',
                fontSize: '11px',
                fontWeight: 600,
                border: '1px solid #b7eb8f',
                boxShadow: '0 1px 2px rgba(82, 196, 26, 0.1)',
                textTransform: 'uppercase',
                letterSpacing: '0.5px'
              }}>
                {parameter.unit}
              </span>
            )}
          </div>
          {sortedValues.length > 10 && (
            <Button
              type="link"
              size="small"
              onClick={() => setIsExpanded(!isExpanded)}
              style={{ 
                padding: 0, 
                height: 'auto', 
                fontSize: '11px',
                color: '#1890ff'
              }}
            >
              {isExpanded ? (
                <>
                  <UpOutlined style={{ marginRight: '2px' }} />
                  收起
                </>
              ) : (
                <>
                  <DownOutlined style={{ marginRight: '2px' }} />
                  展开全部 ({sortedValues.length} 个)
                </>
              )}
            </Button>
          )}
        </div>
      );
    } else {
      // 非列表参数：只显示第一个值
      const firstValue = values[0];
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
          <span style={{ fontSize: '12px', color: '#8c8c8c' }}>值:</span>
          <Tag color="cyan" style={{ 
            fontSize: '11px',
            borderRadius: '8px',
            padding: '2px 8px',
            margin: 0,
            lineHeight: '18px'
          }}>
            {formatParameterValue(firstValue)}
          </Tag>
          {parameter.unit && (
            <span style={{ 
              background: 'linear-gradient(135deg, #f6ffed 0%, #f0f9e8 100%)',
              color: '#52c41a',
              padding: '3px 8px',
              borderRadius: '4px',
              fontSize: '11px',
              fontWeight: 600,
              border: '1px solid #b7eb8f',
              boxShadow: '0 1px 2px rgba(82, 196, 26, 0.1)',
              textTransform: 'uppercase',
              letterSpacing: '0.5px'
            }}>
              {parameter.unit}
            </span>
          )}
        </div>
      );
    }
  };

  return (
    <div 
      className="parameter-item" 
      style={{ 
        display: 'flex', 
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '16px 20px',
        minHeight: 'auto',
        background: 'white',
        border: '1px solid #e8e8e8',
        borderRadius: '6px',
        transition: 'all 0.2s ease',
        boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
        position: 'relative'
      }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <div className="parameter-info" style={{ 
        flex: 1,
        minWidth: 0,
        display: 'flex',
        flexDirection: 'column',
        gap: '8px'
      }}>
        {/* 第一行：参数名称、英文名和类型标签 */}
        <div style={{ 
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          flexWrap: 'wrap'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: '1 1 auto', minWidth: '120px', position: 'relative' }}>
            <span style={{ 
              fontSize: '16px', 
              fontWeight: 500, 
              color: '#262626',
              overflow: 'hidden', 
              textOverflow: 'ellipsis', 
              whiteSpace: 'nowrap'
            }}>
              {parameter.name}
            </span>
            {isHovered && (
              <Button
                type="text"
                size="small"
                icon={<ArrowUpOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  onPinToTop();
                }}
                title="置顶"
                style={{ 
                  position: 'absolute',
                  right: '-8px',
                  top: '-6px',
                  padding: '4px 8px',
                  color: '#8c8c8c',
                  transition: 'all 0.2s ease',
                  zIndex: 10
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.color = '#1890ff';
                  e.currentTarget.style.backgroundColor = 'rgba(24, 144, 255, 0.1)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.color = '#8c8c8c';
                  e.currentTarget.style.backgroundColor = 'transparent';
                }}
              />
            )}
            <Tag 
              color="blue" 
              style={{ 
                fontSize: '12px',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '4px',
                transition: 'all 0.2s ease',
                flexShrink: 0
              }}
              onClick={handleCopyEnglishName}
              onMouseEnter={(e) => {
                e.currentTarget.style.opacity = '0.8';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.opacity = '1';
              }}
            >
              {parameter.name_en}
              <CopyOutlined style={{ fontSize: '10px', opacity: 0.6 }} />
            </Tag>
          </div>
          <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
            <Tag 
              color={getTypeColor(parameter.param_type)}
              style={{ 
                fontSize: '11px', 
                lineHeight: '18px',
                borderRadius: '10px',
                fontWeight: 500,
                flexShrink: 0
              }}
            >
              {getTypeText(parameter.param_type)}
            </Tag>
            {parameter.is_list && (
              <Tag color="cyan" style={{ 
                fontSize: '11px', 
                lineHeight: '18px',
                borderRadius: '10px',
                fontWeight: 500,
                flexShrink: 0
              }}>
                列表 ({parameter.values?.length || 0})
              </Tag>
            )}
            {parameter.is_list && parameter.is_year_related && (
              <Tag color="geekblue" style={{ 
                fontSize: '11px', 
                lineHeight: '18px',
                borderRadius: '10px',
                fontWeight: 500,
                flexShrink: 0
              }}>
                关联年份
              </Tag>
            )}
          </div>
        </div>

        {/* 第三行：描述（如果有） */}
        {parameter.description && (
          <div style={{ 
            fontSize: '12px', 
            color: '#595959',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            background: '#f8f9fa',
            padding: '2px 6px',
            borderRadius: '4px',
            border: '1px solid #e9ecef'
          }}>
            {parameter.description}
          </div>
        )}

        {/* 第四行：参数值 */}
        {renderParameterValues()}
      </div>

      <div className="parameter-actions" style={{ 
        flexShrink: 0,
        marginLeft: '12px',
        display: 'flex',
        alignItems: 'center',
        height: '100%'
      }}>
        <Space size="small">
          <Tooltip title="设置参数值">
            <Button
              type="text"
              size="small"
              icon={<SettingOutlined />}
              onClick={onSetValues}
              style={{ 
                color: '#1890ff',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                width: '28px',
                height: '28px',
                padding: 0
              }}
            />
          </Tooltip>
          <Tooltip title="编辑参数">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={onEdit}
              style={{ 
                color: '#52c41a',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                width: '28px',
                height: '28px',
                padding: 0
              }}
            />
          </Tooltip>
          <Tooltip title="删除参数">
            <Button
              type="text"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={onDelete}
              style={{ 
                border: '1px solid #ff4d4f',
                borderRadius: '4px',
                width: '28px',
                height: '28px',
                padding: 0
              }}
            />
          </Tooltip>
        </Space>
      </div>
    </div>
  );
};

export default ParameterItem;
